﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Besture.Bll;
using Besture.Common;
using Besture.Common.Helper;
using Besture.Model;
using System.Data;
using Besture.UI.ClassHelper;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Data;

namespace Besture.UI
{
    public partial class RoomStatusSet : BasePage
    {
        public DateTime IDataNow = DateTime.Now;

        #region 页面加载事件

        /// <summary>
        /// 页面加载
        /// </summary>
        protected override void InitialLoad()
        {
            //页面加载
            InitPage();
            calendarWrap.Visible = false;
        }

        /// <summary>
        /// 回发
        /// </summary>
        protected override void PostBackLoad()
        {
            InitPage();
        }

        /// <summary>
        /// 页面加载
        /// </summary>
        public void InitPage()
        {
            //早餐情况 绑定
            var vBreakfast = QueryDac.GetTable("SELECT * FROM TBDictionaryType WHERE Type = 5");
            //BindDropDownList(ddl_box_Breakfast, vBreakfast, "name", "code");
        }

        private static void BindDropDownList(DropDownList dropDownList, DataTable sourceTable, string dataTextField, string dataValueField)
        {
            if (sourceTable != null)
            {
                dropDownList.DataSource = sourceTable;
                dropDownList.DataTextField = dataTextField;
                dropDownList.DataValueField = dataValueField;
                dropDownList.DataBind();
            }
        }


        #endregion

        /// <summary>
        /// 日历html
        /// </summary>
        /// <param name="roomId">房型id</param>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public string GetCalendarData(int roomId)
        {
            string tableHtml;
            string sdata = Convert.ToString(IDataNow.Year + "-" + IDataNow.Month);
            int days = System.Threading.Thread.CurrentThread.CurrentUICulture.Calendar.GetDaysInMonth(IDataNow.Year, IDataNow.Month);
            string sHtml = string.Empty;
            for (int i = 1; i <= days; i++)
            {
                //第一行合并表格
                if (i == 1)
                {
                    if (GetWeek(Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month + "-01")) != "7")
                    {
                        sHtml += string.Format("<td colspan={0} class='disabled'></td>",
                            GetWeek(Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month + "-01")));

                    }
                }

                /**
                 * 1.判断是否房间开放 
                 * 2.是否房间关闭
                 * 3.是否限量售卖
                 * 4.是否无房价/不可订
                 * 5.是否大床满 
                 * 6.是否双床满 
                 */

                //1.日历 显示会员价格 并 显示 早餐情况

                //1.判断是否房间开放 
                DateTime data = Convert.ToDateTime(sdata + '-' + i);
                string sdisabled = string.Empty;
                var vdining = ""; //早餐图片默认高亮显示
                var expiredTime = "li-roomCount1"; //过期的日期显示的字体颜色
                if (data.Date < DateTime.Now.Date)
                {
                    sdisabled = "disabled";
                    //vdining = "ico-dining";
                }else if (data >= DateTime.Now)
                {
                    //未过期显示的字体颜色
                    expiredTime = "li-roomCount";
                }

                //2.显示房间数量
                var vPriceModel = new RoomPriceDac().GetModelByRoomIdAndRoomTime(roomId, data);
                //string memberPrice = string.Empty;
                //var vBreakfast = 0;
                var roomQuantity = 0;
                //Title提示
                var roomTitle = "";
                var vLimitedSale = 0;
                if (vPriceModel != null)
                {
                    roomQuantity = vPriceModel.RoomQuantity;
                    //memberPrice = string.Format("{0:N}", vPriceModel.Price); //会员价
                    //3.显示早餐信息
                    //vBreakfast = vPriceModel.Breakfast; //会员价
                    vLimitedSale = vPriceModel.LimitedSale;

                }

                //房间状态
                if (data >= DateTime.Now && vPriceModel != null)
                {
                    //有房
                    if (vPriceModel.HousingState == Constants.HOUSING_STATE_HAVE)
                    {
                        roomTitle = "有房";
                    }
                    //紧张
                    if (vPriceModel.HousingState == Constants.HOUSING_STATE_TENSION)
                    {
                        roomTitle = "紧张";
                        sdisabled = "roomtension";
                    }
                    //客满
                    if (vPriceModel.HousingState == Constants.HOUSING_STATE_FULL)
                    {
                        roomTitle = "客满";
                        sdisabled = "roomfull";
                    }
                }

                //无房价，不可订
                if (data >= DateTime.Now && vPriceModel==null)
                {
                    sdisabled = "disabled"; // 不可点击
                    vdining = "ico-norates";
                    roomTitle = "无房价";
                } 
                //生成td 
                sHtml += string.Format("<td class='{0}' date='{1}' title='{5}'><div>" +
                                           "<ul class='price-list'> " +
                                               " <li class='li-date'>{2}</li>" +
                                               " <li class='{6}'>{3}</li>" +
                                               " <li>{7}</li>" +
                                               " <li class='{4}'><i></i></li>" +
                                           "</ul>" +
                                       "</div></td>", sdisabled, (sdata + '-' + i), i, roomQuantity - vLimitedSale, vdining, roomTitle, expiredTime, vLimitedSale);

                //处理 7天单位 换行
                string weekstr = GetWeek(Convert.ToDateTime(sdata + "-" + i));
                if (weekstr.Equals("6"))
                {
                    //生成td 换行   
                    sHtml = string.Format("<tr>{0}</tr>", sHtml);
                }


            }

            DateTime date = Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month).AddMonths(1).AddDays(-1);
            if (GetWeek(date) != "6")
                tableHtml = sHtml +
                            string.Format("<td colspan='{0}' class='disabled'></td>",
                                7 - Convert.ToInt32(GetWeek(date) == "7" ? "1" : GetWeek(date)));
            else
                tableHtml = sHtml;

            return tableHtml;
        }

        private string GetWeek(DateTime data)
        {
            string weekstr = data.DayOfWeek.ToString();
            switch (weekstr)
            {
                case "Monday": weekstr = "1"; break;
                case "Tuesday": weekstr = "2"; break;
                case "Wednesday": weekstr = "3"; break;
                case "Thursday": weekstr = "4"; break;
                case "Friday": weekstr = "5"; break;
                case "Saturday": weekstr = "6"; break;
                case "Sunday": weekstr = "7"; break;
            }
            return weekstr;
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSeachClick(object sender, EventArgs e)
        {
            var dt = new DataTable();
            string[] sId = hidID.Value.Split('|');

            //0表示显示酒店全部房型 反之1某一个房型
            dt = sId[0] == "0" ? new RoomDac().GetRoomByIDorHotelsId(0, Convert.ToInt32(sId[1]))
                : new RoomDac().GetRoomByIDorHotelsId(Convert.ToInt32(sId[1]), 0);

            string month = hidColendarMonth.Value;
            switch (month)
            {
                case "1":
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + (Convert.ToInt32(txtMonth.Value) - 1));   // 1表示前月份  
                    txtMonth.Value = (Convert.ToInt32(txtMonth.Value) - 1).ToString();
                    break;
                case "2":
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + (Convert.ToInt32(txtMonth.Value) + 1));   //2表示后月份  
                    txtMonth.Value = (Convert.ToInt32(txtMonth.Value) + 1).ToString();
                    break;
                default:
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month);    //默认当月份
                    txtMonth.Value = (IDataNow.Month).ToString();
                    break;
            }


            if (dt.Rows.Count > 0)
                calendarWrap.Visible = true;

            rpRoom.DataSource = dt;
            rpRoom.DataBind();

            //绑定数据后重新注册一下JS事件
            GetRegister();
        }


        /// <summary>
        /// 绑定数据后重新注册一下JS事件
        /// </summary>
        private void GetRegister()
        {
            //绑定数据后重新注册一下JS事件getUpdateHotels();getBtnBlue();
            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel2, GetType(), "getUpdateHotels",
               "GetInLoadCalendar();GetQuery();setTab(this,0);", true);
        }


        //处理价格事件
        protected void BtnSavePriceClick(object sender, EventArgs e)
        {
            try
            {
                var dac = new RoomPriceDac();
                RoomPriceModel model = new RoomPriceModel();
                var baseDac = new BaseDac<RoomPriceModel>();
                int lsRecord = 0;
                string[] sRoomId = hidRoom.Value.Split('|');
                if (sRoomId.Length > 0)
                {
                    model.RoomID = Convert.ToInt32(sRoomId[0]);
                    
                    string[] sRoomTime = sRoomId[1].TrimEnd(',').Split(',');
                    foreach (string t in sRoomTime)
                    { 
                        model = new RoomPriceDac().GetModelByRoomIdAndRoomTime(model.RoomID, Convert.ToDateTime(t));
                        if (model != null)
                        { 
                            #region 修改房间状态
                            if (!rabNotUpdate.Checked)
                            {
                                //有房
                                if (rabHouse.Checked)
                                {
                                    model.HousingState = Constants.HOUSING_STATE_HAVE;
                                }
                                //紧张
                                if (rabTension.Checked)
                                {
                                    model.HousingState = Constants.HOUSING_STATE_TENSION;
                                }
                                //紧张
                                if (rabFullHouse.Checked)
                                {
                                    model.HousingState = Constants.HOUSING_STATE_FULL;
                                }
                            }
                            #endregion

                            #region  修改房间数量
                            if (!rabNumber.Checked)
                            {
                                //增加房间
                                if (rabAddRoom.Checked)
                                {
                                    model.RoomQuantity = model.RoomQuantity +
                                        Convert.ToInt32(string.IsNullOrEmpty(txtAddNumber.Text.Trim()) ? "0" : txtAddNumber.Text.Trim());
                                }
                                //减少房间
                                if (rabCutBack.Checked)
                                {
                                    if (Convert.ToInt32(string.IsNullOrEmpty(txtCutBackNumber.Text.Trim()) ? "0" : txtCutBackNumber.Text.Trim()) > model.RoomQuantity)
                                    {
                                        FunHelper.Alert("减少的房间数不能大于当前 " + model.RoomQuantity + " 房间数", Request.Url.ToString());
                                        return;
                                    }
                                    model.RoomQuantity = model.RoomQuantity -
                                        Convert.ToInt32(string.IsNullOrEmpty(txtCutBackNumber.Text.Trim()) ? "0" : txtCutBackNumber.Text.Trim());
                                }
                            }
                            #endregion

                            model.LimitedSale = Convert.ToInt32(txtLimitedSale.Text);//限量售卖 
                            model.RoomTime = Convert.ToDateTime(t);
                            baseDac.LoadUpdateBaseModel(model);
                            lsRecord = dac.UpdateRoomStatusAndRoomTime(model);
                        } 
                    }
                    if (lsRecord > 0)
                        FunHelper.Alert("保存成功",Request.Url.ToString());
                    else
                        FunHelper.Alert("该日期没有设置价格,不能设置房态信息");
                }
            }
            catch (Exception)
            {
                FunHelper.Alert("保存失败!");
            } 
            GetRegister();
        }
    }
}